//
//  YBCloudComputerVC.swift
//  Moonlight
//
//  Created by Penlon Kim on 2023/6/5.
//  Copyright © 2023 Moonlight Game Streaming Project. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyJSON
import HandyJSON
import EachNavigationBar
import SVProgressHUD

class YBCloudComputerVC: BaseVC {

    enum ViewType: Int {
        case tabbar = 1 // Tabbar
        case center = 2 // 个人中心
        
        var des: String {
            switch self {
            case .tabbar: return "首页"
            case .center: return "设备"
            }
        }
    }
    
    private var viewType: YBCloudComputerVC.ViewType = .tabbar
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    init(viewType: YBCloudComputerVC.ViewType) {
        super.init(nibName: nil, bundle: nil)
        self.viewType = viewType
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigation.item.title = viewType.des
        
        if viewType == .tabbar {
            navigation.item.leftBarButtonItem = UIBarButtonItem(customView: faultRepairBtn)
            let newsItem = UIBarButtonItem(customView: newsBtn)
            let refreshItem = UIBarButtonItem(customView: refreshBtn)
            navigation.item.rightBarButtonItems = [newsItem, refreshItem]
        }

        view.backgroundColor = .lightGray242Dark17
        
        tableView.bk_addRefreshHeader {
            self.get_userOrderInfo()
        }
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        if viewType == .tabbar {
            self.tableView.bk_setHeaderFooter(headerV: tableHeader)
        }
        
        self.get_userOrderInfo()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.bk_setPopSwipe(false)
        NOC.default.post(name: .NotiKeyEnterApp.DidAppear, object: nil)
    }
    
    // MARK: - lazy
    lazy var vm: YBCloudComputerViewModel = {
        let vm = YBCloudComputerViewModel()
        return vm
    }()
    
    private lazy var tableView: BKGestureTableView = {
        let tv = BKGestureTableView(frame: .zero, style: .grouped)
        tv.estimatedRowHeight = 44
        tv.rowHeight = UITableView.automaticDimension
        tv.delegate = self
        tv.dataSource = self
        tv.gestureDelegate = self
        tv.separatorStyle = .none
        tv.showsVerticalScrollIndicator = false
        if #available(iOS 15.0, *) {
            tv.sectionHeaderTopPadding = 0
        }
        tv.register(cellWithClass: YBCloudComputerCell.self)
        return tv
    }()
    
    private lazy var tableHeader: YBCloudComputerTableHeader = {
        let header = YBCloudComputerTableHeader()
        return header
    }()
    
    /// 反馈
    private lazy var faultRepairBtn: BKLayoutButton = {
        let btn = self.bk_addGradientLayoutButton(style: .leftTitleRightImage, space: 6, bgColor: .clear, imageSize: CGSizeMake(14, 14), image: UIImage(named: "icon_cloudcomputer_fault"), titleFont: .systemFont(ofSize: 12, weight: .medium), title: "故障反馈", titleColor: .white, gradientSize: CGSizeMake(80, 26), colors: [kRGBColor(88, 182, 255), kRGBColor(40, 128, 237)])
        btn.bk_addTarget { [weak self] button in

            let vc = YBCloudComputerFeedbackPopupVC()
            vc.configBlock = { [weak self] text, type in
                let parm = ["content": text, "type": type + 1]
                self?.vm.req_gzbx(parm) { ok, obj, msg, code in
                    if ok {
                        HintTool.toast("反馈成功")
                    }else {
                        HintTool.toast(msg)
                    }
                }
            }
            self?.present(vc, animated: true)
        }
        return btn
    }()
    
    /// 消息通知
    private lazy var newsBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "icon_cloudcomputer_news"), for: .normal)
        btn.bk_addTarget { [weak self] sender in
            let messageVC = YBMessageVC()
            self?.navigationController?.pushViewController(messageVC, animated: true)
        }
        return btn
    }()
    
    /// 刷新
    private lazy var refreshBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "icon_shuaxin"), for: .normal)
        btn.bk_addTarget { [weak self] sender in
            self?.vm.req_Reset({ ok, obj, msg, code in
                if ok {
                    HintTool.toast("重置成功")
                }else {
                    HintTool.toast(msg)
                }
            })
        }
        return btn
    }()
    
    /// 网络诊断
    private lazy var networkDiagnosisBtn: BKLayoutButton = {
        let btn = self.bk_addLayoutButton(space: 2, bgColor: .clear, imageSize: CGSizeMake(16, 16), image: UIImage(named: "icon_cloudcomputer_issue"), titleFont: .systemFont(ofSize: 12, weight: .bold), title: "网络诊断", titleColor: ColorDef.gray102)
        btn.isHidden = true
        btn.bk_addTarget { sender in
            NetStatusTool.shared.monitor { status in
                HintTool.toast(status.rawValue)
            }
        }
        return btn
    }()
    
}

// MARK: - BKGestureTableViewDelegate
extension YBCloudComputerVC: BKGestureTableViewDelegate {
    
    func gestureTableViewGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        // 禁止banner左右滑动的时候,上下左右都可以滚动
        if otherGestureRecognizer == tableHeader.cardView._collectionView.panGestureRecognizer { return false }
        return gestureRecognizer is UIPanGestureRecognizer && otherGestureRecognizer is UIPanGestureRecognizer
    }
    
}

// MARK: - UITableView代理
extension YBCloudComputerVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return viewType == .tabbar ? 0.01 : 10
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return vm.orderInfoVosModels.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YBCloudComputerCell.self, for: indexPath)
        let model = vm.orderInfoVosModels[indexPath.section]
        cell.updateCell(by: model)
        
        // 点击开机
        cell.powerOnBlock = {
            if model.purchase {
                self.powerOnPc(model)
            } else {
                let vc = YBCloudComputerBuyVC(goodsId: model.goodsId)
                self.navigationController?.pushViewController(vc)
            }
        }
        
        // 故障报修
        cell.faultRepairBtnBlock = {
           let parm = ["content": "PC故障", "type": "1"]
            self.vm.req_gzbx(parm) { ok, obj, msg, code in
                if ok {
                    HintTool.toast("申报成功")
                }else {
                    HintTool.toast(msg)
                }
            }
        }
        
        // 重置
        cell.resetBtnBlock = {
            self.vm.req_Reset { ok, obj, msg, code in
                if ok {
                    HintTool.toast("重置成功")
                }else {
                    HintTool.toast(msg)
                }
            }
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard !vm.orderInfoVosModels.isEmpty else { return }
        let model = vm.orderInfoVosModels[indexPath.section]
        if model.purchase == false {
            let vc = YBCloudComputerBuyVC(goodsId: model.goodsId)
            self.navigationController?.pushViewController(vc)
        } else {
            self.powerOnPc(model)
        }
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let shapeLayer = CAShapeLayer()
        cell.layer.mask = nil
        let bezierPath = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 4, height: 4))
        shapeLayer.path = bezierPath.cgPath
        cell.layer.mask = shapeLayer
    }
    
}

// MARK: - 网络请求
extension YBCloudComputerVC {

    fileprivate func get_userOrderInfo() {
        vm.req_userOrderInfo { [weak self] ok, obj, msg, code in
            self?.tableView.bk_endMJRefresh()
            if ok {
                guard let js = obj as? JSON,
                      let data = js[NetDataKey]["orderInfoVos"].arrayObject,
                      let models = [YBUserModel.OrderInfoVos].deserialize(from: data) as? [YBUserModel.OrderInfoVos] else { return }
                self?.vm.orderInfoVosModels = models
                self?.tableView.reloadData()
            } else {
                HintTool.toast(msg)
            }
        }
    }
    
    /// 开机
    func powerOnPc(_ model: YBUserModel.OrderInfoVos) {
        SVProgressHUD.show(withStatus: "开机中...")
        let params = ["goodsId": model.goodsId,
                      "gpuName": model.gpuName,
                      "gpuType": model.gpuType,
                      "orderInfoId": model.id,
                      "type": model.type,
                      "userId": model.userId] as [String : Any]
        vm.req_OpenPC(params) { [self] ok, obj, msg, code in
            SVProgressHUD.dismiss()
            if ok {
                guard let js = obj as? JSON,
                      let data = js[NetDataKey].dictionaryObject,
                      let pairModel = YBPairModel.deserialize(from: data) else { return }
                
                // 处理端口转换
                YBPortManager.deal(withNtpcport: pairModel.ntpcport,
                                   wtpcport: pairModel.wtpcport,
                                   nudpport: pairModel.nudpport,
                                   wudpport: pairModel.wudpport)

                // 跳转
                DispatchQueue.main.async {
                    let vc = YBCloudComputerDetailVC(model: model, pairModel: pairModel) // infoModel && pairModel
                    self.navigationController?.pushViewController(vc)
                }
            } else {
                SVProgressHUD.dismiss()
                HintTool.toast(msg)
            }
        }
    }
    
}
